<template>
  <div class="club-members-container">
    <div class="section-header">
      <h2>成员管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索成员"
          prefix-icon="el-icon-search"
          clearable
          @clear="loadMembers"
          class="search-input"
        ></el-input>
        <el-button type="primary" @click="searchMembers">搜索</el-button>
      </div>
    </div>

    <!-- 成员列表 -->
    <el-table
      :data="members"
      style="width: 100%"
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
    >
      <el-table-column label="头像" min-width="100">
        <template #default="scope">
          <img
            :src="(scope.row.avatar ? scope.row.avatar : '../../../src/assets/erji.png')"
            alt="用户头像"
            style="width: 50px; height: 50px; border-radius: 50%;"
          >
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" min-width="100"></el-table-column>
      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column prop="gender" label="性别" min-width="80"></el-table-column>
      <el-table-column prop="studentId" label="学号" min-width="150"></el-table-column>
      <el-table-column prop="college" label="学院" min-width="150"></el-table-column>
      <el-table-column prop="className" label="班级" min-width="150"></el-table-column>
      <el-table-column prop="hobbies" label="兴趣爱好" min-width="150"></el-table-column>
      <el-table-column prop="role" label="职位" min-width="120">
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">{{ scope.row.role }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" min-width="150"></el-table-column>
      <el-table-column prop="joinTime" label="加入时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.joinTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="382" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="info"
            @click="viewMemberDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="small"
            type="primary"
            @click="changeRole(scope.row)"
          >更改职位</el-button>
          <el-button
            size="small"
            type="warning"
            @click="setAdmin(scope.row)"
            v-if="!isAdmin(scope.row.id)"
          >设为管理员</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmRemove(scope.row)"
            :disabled="scope.row.role === '社长'"
          >移出社团</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 更改职位对话框 -->
    <el-dialog
      title="更改成员职位"
      v-model="showRoleDialog"
      width="30%"
    >
      <div v-if="selectedMember">
        <p>成员: <strong>{{ selectedMember.name }}</strong></p>
        <p>当前职位: <strong>{{ selectedMember.role }}</strong></p>
        <el-divider></el-divider>
        <el-select v-model="newRole" placeholder="选择新职位">
          <el-option
            v-for="role in roleOptions"
            :key="role.value"
            :label="role.label"
            :value="role.value"
          ></el-option>
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="updateRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置管理员确认对话框 -->
    <el-dialog
      title="设置社团管理员"
      v-model="showAdminDialog"
      width="30%"
    >
      <p>确定要将 <strong>{{ selectedMember?.name }}</strong> 设为社团管理员吗？</p>
      <p>管理员可以管理社团成员、活动和帖子。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAdminDialog = false">取消</el-button>
          <el-button type="warning" @click="updateAdmin">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 移出成员确认对话框 -->
    <el-dialog
      title="移出社团成员"
      v-model="showRemoveDialog"
      width="30%"
    >
      <p>确定要将 <strong>{{ selectedMember?.name }}</strong> 移出社团吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRemoveDialog = false">取消</el-button>
          <el-button type="danger" @click="removeMember">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成员详情对话框 -->
    <el-dialog
      title="成员详情"
      v-model="showDetailDialog"
      width="50%"
    >
      <div v-if="selectedMember" class="member-detail">
        <div class="member-header">
          <div class="member-avatar">
            <img :src="selectedMember.avatar || '../../components/icons/touxiang.png'" alt="用户头像">
          </div>
          <div class="member-info">
            <h3>{{ selectedMember.name }} ({{ selectedMember.username }})</h3>
            <p>
              <el-tag :type="getRoleTagType(selectedMember.role)">{{ selectedMember.role }}</el-tag>
              <span class="join-time">加入时间: {{ formatDate(selectedMember.joinTime) }}</span>
            </p>
          </div>
        </div>

        <el-divider></el-divider>

        <div class="detail-item">
          <span class="label">学号:</span>
          <span class="value">{{ selectedMember.studentId }}</span>
        </div>

        <div class="detail-item">
          <span class="label">学院:</span>
          <span class="value">{{ selectedMember.college }}</span>
        </div>

        <div class="detail-item">
          <span class="label">班级:</span>
          <span class="value">{{ selectedMember.className }}</span>
        </div>

        <div class="detail-item">
          <span class="label">性别:</span>
          <span class="value">{{ selectedMember.gender }}</span>
        </div>

        <div class="detail-item" v-if="selectedMember.hobbies">
          <span class="label">兴趣爱好:</span>
          <span class="value">{{ selectedMember.hobbies }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button type="primary" @click="changeRole(selectedMember)">更改职位</el-button>
          <el-button
            type="danger"
            @click="confirmRemove(selectedMember)"
            :disabled="selectedMember?.role === '社长'"
          >移出社团</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 接收社团ID属性
const props = defineProps({
  clubId: {
    type: [String, Number],
    required: true
  }
})

// 状态变量
const loading = ref(false)
const members = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const showRoleDialog = ref(false)
const showAdminDialog = ref(false)
const showRemoveDialog = ref(false)
const showDetailDialog = ref(false)
const selectedMember = ref(null)
const newRole = ref('')
const admins = ref([]) // 管理员ID列表

// 职位选项
const roleOptions = [
  { label: '社长', value: '社长' },
  { label: '副社长', value: '副社长' },
  { label: '宣传部长', value: '宣传部长' },
  { label: '组织部长', value: '组织部长' },
  { label: '秘书部长', value: '秘书部长' },
  { label: '成员', value: '成员' }
]

// 获取角色标签类型
const getRoleTagType = (role) => {
  switch (role) {
    case '社长': return 'danger'
    case '副社长': return 'warning'
    case '宣传部长':
    case '组织部长':
    case '秘书部长': return 'success'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';

  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
};

// 判断是否为管理员
const isAdmin = (userId) => {
  console.log('检查是否为管理员:', userId)
  console.log('管理员列表:', admins.value)
  return admins.value.includes(userId)
}

// 加载成员数据
const loadMembers = async () => {
  loading.value = true
  try {
    // 获取社团成员
    const response = await axios.get(`http://localhost:5000/clubs/${props.clubId}/members`);
    members.value = response.data || [];
    totalItems.value = members.value.length;

    // 获取社团管理员列表
    const clubResponse = await axios.get(`http://localhost:5000/clubs/${props.clubId}`);
    if (clubResponse.data && clubResponse.data.admin) {
      admins.value = Array.isArray(clubResponse.data.admin)
        ? clubResponse.data.admin
        : [clubResponse.data.admin];
    }

    loading.value = false;
  } catch (error) {
    console.error('加载成员失败', error)
    ElMessage.error('加载成员失败')
    loading.value = false
  }
}

// 搜索成员
const searchMembers = () => {
  if (!searchQuery.value.trim()) {
    loadMembers()
    return
  }

  loading.value = true
  const query = searchQuery.value.toLowerCase()

  // 本地过滤搜索结果
  const filteredMembers = members.value.filter(member =>
    member.name?.toLowerCase().includes(query) ||
    member.username?.toLowerCase().includes(query) ||
    member.studentId?.includes(query) ||
    member.college?.toLowerCase().includes(query)
  )

  members.value = filteredMembers
  totalItems.value = filteredMembers.length
  loading.value = false
}

// 查看成员详情
const viewMemberDetail = (member) => {
  selectedMember.value = member
  showDetailDialog.value = true
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadMembers()
}

// 更改职位
const changeRole = (member) => {
  selectedMember.value = member
  newRole.value = member.role
  showRoleDialog.value = true
}

// 更新职位
const updateRole = async () => {
  if (!selectedMember.value || !newRole.value) return

  try {
    console.log('更新成员职位:', selectedMember.value);
    console.log('成员ID:', selectedMember.value.id);
    console.log('新职位:', newRole.value);

    // 发送请求更新成员角色
    const response = await axios.put(`http://localhost:5000/clubs/${props.clubId}/members/${selectedMember.value.id}`, {
      role: newRole.value
    });

    console.log('服务器响应:', response.data);

    // 更新本地数据
    const index = members.value.findIndex(m => m.id === selectedMember.value.id);
    if (index !== -1) {
      members.value[index].role = newRole.value;
    } else {
      console.error('无法在本地数据中找到成员，id:', selectedMember.value.id);
      console.log('当前成员列表:', members.value);
    }

    ElMessage.success('职位更新成功');
    showRoleDialog.value = false;

    // 如果详情对话框打开，更新详情中的角色
    if (showDetailDialog.value) {
      selectedMember.value.role = newRole.value;
    }
  } catch (error) {
    console.error('更新职位失败', error);
    const errorMsg = error.response?.data?.message || '更新职位失败';
    ElMessage.error(errorMsg);
  }
}

// 设置管理员
const setAdmin = (member) => {
  selectedMember.value = member
  showAdminDialog.value = true
}

// 更新管理员
const updateAdmin = async () => {
  if (!selectedMember.value) return

  try {
    console.log('设置管理员:', selectedMember.value);
    console.log('用户ID:', selectedMember.value.id);

    // 发送请求更新社团管理员
    const response = await axios.put(`http://localhost:5000/clubs/${props.clubId}/admins`, {
      userId: selectedMember.value.id
    });

    console.log('服务器响应:', response.data);

    // 更新本地数据
    admins.value.push(selectedMember.value.id);

    ElMessage.success('管理员设置成功');
    showAdminDialog.value = false;
  } catch (error) {
    console.error('设置管理员失败', error);
    const errorMsg = error.response?.data?.message || '设置管理员失败';
    ElMessage.error(errorMsg);
  }
}

// 确认移出成员
const confirmRemove = (member) => {
  selectedMember.value = member
  showRemoveDialog.value = true

  // 如果详情对话框打开，关闭它
  if (showDetailDialog.value) {
    showDetailDialog.value = false;
  }
}

// 移出成员
const removeMember = async () => {
  if (!selectedMember.value) return

  try {
    console.log('移出成员:', selectedMember.value);
    console.log('成员ID:', selectedMember.value.id);

    // 发送请求删除成员
    const response = await axios.delete(`http://localhost:5000/clubs/${props.clubId}/members/${selectedMember.value.id}`);

    console.log('服务器响应:', response.data);

    // 从本地数据中移除
    members.value = members.value.filter(m => m.id !== selectedMember.value.id);

    // 如果是管理员，从管理员列表中移除
    if (isAdmin(selectedMember.value.id)) {
      admins.value = admins.value.filter(id => id !== selectedMember.value.id);
    }

    ElMessage.success('成员已移出社团');
    showRemoveDialog.value = false;
  } catch (error) {
    console.error('移出成员失败', error);
    const errorMsg = error.response?.data?.message || '移出成员失败';
    ElMessage.error(errorMsg);
  }
}

onMounted(() => {
  loadMembers()
})
</script>

<style scoped>
.club-members-container {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #ffffff;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 成员详情样式 */
.member-detail {
  padding: 10px;
}

.member-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.member-avatar {
  margin-right: 20px;
}

.member-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.1);
}

.member-info h3 {
  margin: 0 0 10px 0;
  color: #ffffff;
}

.join-time {
  margin-left: 15px;
  color: #b0bec5;
  font-size: 14px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-item .label {
  width: 100px;
  color: #b0bec5;
  flex-shrink: 0;
}

.detail-item .value {
  color: #ffffff;
  flex: 1;
}
</style>
